<?php
//header('Content-Type: application/json');

/*
$srd=fopen('php://input', 'r');
$swd=fopen('post.json','a');
stream_copy_to_stream($srd,$swd);
*/

require_once 'config.php';
require_once 'Core/Session.php';
require_once 'Class/RST.php';

if(isset($_GET['m']))$m=$_GET['m'];
if(isset($_GET['a']))$a=$_GET['a'];
if(!isset($m)||$m==null||!isset($a)||$a==null)
	exit();
if($m!='Certificate' || ($a!='login' && $m='Certificate')){
	$o=SESSION::Certificate();
	if($o===null){
		$o=new RST();
		$o->RSTCode=401;
		$o->RSTMessage='Unauthorized';
		echo json_encode($o);
		return;
	}
}
if(!file_exists('Modules/'.$m.'.php')){
	$o=new RST();
	$o->RSTCode=404;
	$o->RSTMessage='Not Found';
	echo json_encode($o);
}
require_once 'Modules/'.$m.'.php';

$obj='M_'.$m;
$obj=new $obj;


if(!method_exists($obj, $a)){
	$o=new RST();
	$o->RSTCode=405;
	$o->RSTMessage='Method Not Allowed';
	echo json_encode($o);
	return;
}

try{
	$o=new RST();
	$o->RSTCode=200;
	$o->RSTCode='OK';
	$o->RSTData=call_user_func_array(array($obj,$a),array(json_decode(file_get_contents('php://input'))));
	
	/*
	$var='{"Id":null,"Name":"Admin","Password":"132456789","Permissions":0,"CreateDate":-62135596800,"ModifyDate":-62135596800,"Status":0}';
	if($var==file_get_contents("php://input")){
		file_put_contents('true.txt', $var.'_'.file_get_contents("php://input"));
	}else
	{
		file_put_contents('false.txt', $var.'_'.file_get_contents("php://input"));
	}
	$o->RSTData=call_user_func_array(array($obj,$a),array(json_decode($var)));
	*/
	echo (json_encode($o));
}catch(Exception $e){	
	$o=new RST();
	$o->RSTCode=403;
	$o->RSTMessage='Forbidden';
	echo (json_encode($o));
}
?>